package io.adrainty.framework.job.configuration;

import com.xxl.job.core.biz.AdminBiz;
import com.xxl.job.core.biz.client.AdminBizClient;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import io.adrainty.framework.job.properties.XxlJobProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/5/6 下午10:33
 */

@Configuration
@EnableConfigurationProperties({
        XxlJobProperties.class
})
public class XxlJobConfig {

    @Bean(name = "xxlJobExecutor")
    @ConditionalOnMissingBean(XxlJobSpringExecutor.class)
    public XxlJobSpringExecutor xxlJobExecutor(ApplicationContext ctx, XxlJobProperties properties) {
        XxlJobSpringExecutor executor = new XxlJobSpringExecutor();
        executor.setAdminAddresses(properties.getAdminAddresses());
        executor.setAppname(StringUtils.defaultIfBlank(properties.getAppName(), ctx.getApplicationName()));
        if (StringUtils.isNotBlank(properties.getAccessToken())) executor.setAccessToken(properties.getAccessToken());
        return executor;
    }

    @Bean(name = "xxlJobAdminBiz")
    @ConditionalOnMissingBean(AdminBiz.class)
    public AdminBiz xxlJobAdminBiz(XxlJobProperties properties) {
        return new AdminBizClient(
                properties.getAdminAddresses(), properties.getAccessToken(), properties.getRequestTimeout()
        );
    }

}
